package com.bianguo.android.tencentpushdemo.tasks;

import android.os.AsyncTask;

import com.bianguo.android.tencentpushdemo.entity.Weather;
import com.bianguo.android.tencentpushdemo.utils.MyLog;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Administrator on 2017/7/10.
 */

public class LoadWeatherTask extends AsyncTask<String, Void, ArrayList<Weather>> {

    private LoadWeatherListener listener;

    public LoadWeatherTask(LoadWeatherListener listener) {
        this.listener = listener;
    }

    @Override
    protected ArrayList<Weather> doInBackground(String... params) {
        ArrayList<Weather> weathers = new ArrayList<>();
        if (params != null) {
            String weatherUrl = params[0];
            try {
                Document document = Jsoup.connect(weatherUrl).timeout(5000).post();
                Elements elements = document.select("div.ui_newlist_1").select("ul").select("li");
                for (Element element : elements) {
                    Weather weather = new Weather();
                    String imageUrl = element.select("div.pic").select("a").select("img").attr("data-src");
                    weather.setImageUrl(imageUrl);
                    Elements detailElement = element.select("div.detail");
                    String title = detailElement.select("h2").select("a").text();
                    weather.setTitle(title);
                    String subTitle = detailElement.select("p.subline").select("a").text();
                    weather.setSubTitle(subTitle);
                    String content = detailElement.select("p.subcontent").text();
                    weather.setContent(content);
                    weathers.add(weather);
                }
            } catch (IOException e) {
                MyLog.myLog("loadWeatherTask error:" + e.getMessage());
                e.printStackTrace();
            }
        }
        return weathers;
    }

    @Override
    protected void onPostExecute(ArrayList<Weather> weathers) {
        if (listener != null) {
            listener.loadWeather(weathers);
        }
    }

    public interface LoadWeatherListener{
        void loadWeather(ArrayList<Weather> weathers);
    }
}
